#include<iostream>
using namespace std;
#include<unistd.h>
#include<vector>
#include<stdlib.h>
#include<sys/wait.h>
#include<stdio.h>
#include<error.h>
#include<time.h>
#include<string>

vector<int> data;

enum{
    OK = 0,
    OPEN_FILE_ERROR = 1,
};

int savebegin()
{
    string name = to_string(time(nullptr));
    name+=".backup";
    FILE* fp = fopen(name.c_str(),"w");
    if(fp==nullptr)
    {
        return OPEN_FILE_ERROR;
    }else
    {
        string str;
        for(auto& e : data)
        {
            str+=to_string(e);
            str+=" ";
        }
        fputs(str.c_str(),fp);
        fclose(fp);
    }
    return OK;
}
void save()
{
    pid_t id = fork();
    if(id==0)
    {
        int code = savebegin();
        exit(code);
    }else
    {
        int status = 0;
        int rid = waitpid(id,&status,0);
        if(rid>0)
        {
            int code = WEXITSTATUS(status);
            if(code == 0)
                printf("备份成功,exit code:%d\n",code);
            else
                printf("备份失败,exit code:%d\n",code);
        }else
        {
            perror("waitpid");
        }
    }


}

int main()
{
    int cnt = 1;
    while(true)
    {
        sleep(1);
        data.push_back(cnt++);
        if(cnt%10==0)
        {
            save();
        }
    }
    return 0;
}

